package wikitools.servlet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.util.Properties;

import javax.servlet.http.HttpServletResponse;

public class ServletUtil {
	public static void useProxy(final String usr, final String pwd) {
		Properties sysprops = System.getProperties();
		sysprops.put("proxySet", "true");
		sysprops.put("http.proxyHost", "wwwproxy.student.unimelb.edu.au");
		sysprops.put("http.proxyPort", "8000");

		Authenticator auth = new Authenticator() {
			public PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(usr, pwd.toCharArray());
			}
		};
		Authenticator.setDefault(auth);
	}

	public static void useProxy() {
		Properties sysprops = System.getProperties();
		sysprops.put("proxySet", "true");
		sysprops.put("http.proxyHost", "wwwproxy.student.unimelb.edu.au");
		sysprops.put("http.proxyPort", "8000");

		Authenticator auth = new Authenticator() {
			public PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication("zhaop", ""
						.toCharArray());
			}
		};
		Authenticator.setDefault(auth);
	}

	public static String toAlertString(String msg) {
		return "<script type=\"text/javascript\">alert('" + msg
				+ "');</script>";

	}

	public static void alert(String msg, HttpServletResponse response)
			throws IOException {
		response.getWriter().write(toAlertString(msg));
	}

	public static void write(String msg, HttpServletResponse response)
			throws IOException {
		response.getWriter().write(msg);
	}

	/**
	 * Get web page content from a url
	 * @param page The URL object of the target web page.
	 * @return String of the page content.
	 */
	public static String content(URL page) {
		StringBuilder sb = new StringBuilder();
		System.out.println("SB___: " + sb.toString());
		try {

			// open a reader for the URL.
			BufferedReader br = new BufferedReader(new InputStreamReader(page
					.openStream()));
			// read by line and build the content string
			String line = br.readLine();
			while (line != null) {
				sb.append(line);
				line = br.readLine();
				
			}
		} catch (IOException e) {
			System.err.println("Error reading URL content: " + e.getMessage());
			e.printStackTrace();
		}
		return sb.toString();
	}
	
	public static void writeXML(String xml, HttpServletResponse response)throws IOException{
		response.setContentType("text/xml");
		ServletUtil.write(xml, response);
		
	}
	
	
}
